<script setup lang="ts">
import { Video } from "../../index";

const props = defineProps<{ video: Video }>();

import { ref } from "vue";
import useSectionStore from "../../store/sectionStore";
import { updateVideoAPI } from "../../api/section";
import { ElMessage } from "element-plus";

const title = ref<string>(props.video.title);

const emits = defineEmits(["update-already"]);

const sectionStore = useSectionStore();

interface ChapterQuestion {
  title: string;
  index: number;
}

interface SectionQuestion {
  id: number;
  title: string;
}

const chapters = ref<ChapterQuestion[]>([]);
const sections = ref<[item?: SectionQuestion[]]>([]);

const chapter = ref();
const section = ref<number>();

sectionStore.getAllChapter().then(() => {
  sectionStore.chapters.forEach((item, index) => {
    chapters.value.push({
      title: item.title,
      index,
    });
    sections.value.push([]);
    item.sections.forEach((it) => {
      sections.value[index].push({
        id: it.id,
        title: it.title,
      });
      if (it.id === props.video.sectionID) {
        chapter.value = index;
        section.value = it.id;
      }
    });
  });
});

const handleChapterChange = () => {
  section.value = null;
};

const update = () => {
  updateVideoAPI({
    id: props.video.id,
    title: title.value,
    section: section.value ?? 0,
  })
    .then((response) => {
      if (response.status !== 200) {
        throw new Error("网络错误");
      }
      return response.data;
    })
    .then((result) => {
      // console.log(result);
      if (result.code === 40101) {
        ElMessage.error("请登录管理员账号");
      }
      if (result.data) {
        ElMessage.success({
          message: "修改成功",
        });
        emits("update-already");
      }
    });
};
</script>

<template>
  <el-form :label-position="'top'">
    <el-form-item label="视频标题: ">
      <el-input type="text" v-model="title" />
    </el-form-item>
    <el-form-item label="选择小节">
      <el-select v-model="chapter" @change="handleChapterChange">
        <el-option
          v-for="t_chapter in chapters"
          :key="t_chapter.index"
          :label="t_chapter.title"
          :value="t_chapter.index"
        />
      </el-select>
      <el-select v-model="section" class="ml-3">
        <el-option
          v-for="t_section in sections[chapter]"
          :key="t_section.id"
          :label="t_section.title"
          :value="t_section.id"
        />
      </el-select>
    </el-form-item>
    <el-button type="primary" @click="update">修改</el-button>
  </el-form>
</template>

<style scoped></style>
